package demo.controller;

import org.springframework.context.ApplicationContext;

/**
 * This class exists to allow for statically obtaining an application
 * context for looking up beans.
 * Any object responsible for creating the application context will register
 * it with this class, guaranteeing an application context is available at any time.
 * Because of the lifecycle of creating the context, the set method should only
 * be called once for a given classloader
 *
 */
public class DemoSpringApplicationContextUtil {
    private static ApplicationContext context;

    /**
     * Should only be called once for a given classloader, at the time the application
     * context is created.  Will throw an exception if this assertion is violated.
     */
    public static synchronized void setApplicationContext(ApplicationContext context) {
        if (DemoSpringApplicationContextUtil.context != null) {
            throw new RuntimeException("Shouldn't need to set context twice, this is" +
                     " a programming error till proven otherwise");
        }
        DemoSpringApplicationContextUtil.context = context;
    }

    public static ApplicationContext getContext() {
        return context;
    }
    
    public static <T> T getBean(String beanName, Class <T> clazz) {
        return (T) context.getBean(beanName, clazz);
    }
    
}
